#include <iostream>
#include <vector>
#include <string>
#include <pthread.h>
#include <unistd.h>

#define NUM 5

int cnt = 100;

pthread_mutex_t glock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;

void* threadrun(void* args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&glock); // 获取锁
        pthread_cond_wait(&gcond, &glock); // 等待条件变量（会自动释放锁！）

        std::cout << name << "计算: " << cnt++ << std::endl; // 被唤醒后执行任务
        pthread_mutex_unlock(&glock); // 释放锁
    }
}

int main()
{
    std::vector<pthread_t> threads;
    for(int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        char* name = new char[64];
        snprintf(name, 64, "thread-%d", i+1);
        int n = pthread_create(&tid, nullptr, threadrun, name);
        if(n != 0) continue;
        threads.push_back(tid);
        sleep(1);
    }
    sleep(3);

    while(true)
    {
        std::cout << "唤醒一个线程..." << std::endl;
        pthread_cond_signal(&gcond);
        sleep(1);
    }

    for(auto& id : threads)
    {
        int n = pthread_join(id, nullptr);
        (void)n;// 返回值不做判断，基本都不会失败
    }
    return 0;
}